<template>
  <div>
    <NavigationBar />
    <div class="page-container">
      <div class="adoption-progress-container">
        <h1>领养进度</h1>
        <div v-if="adoptionProgress.length > 0" class="progress-list">
          <div v-for="progress in adoptionProgress" :key="progress.id" class="progress-card">
            <div class="progress-header">
              <div class="pet-info">
                <img v-if="progress.pet?.image" :src="getImageUrl(progress.pet.image)" class="pet-thumbnail" />
                <h2>{{ progress.pet?.name || '未知宠物' }}</h2>
              </div>
              <span class="status-badge" :class="getStatusClass(progress.status)">{{ progress.status }}</span>
            </div>
            
            <!-- 进度流程条 -->
            <div class="progress-track">
              <div class="progress-steps">
                <div 
                  v-for="(step, index) in adoptionSteps" 
                  :key="index"
                  class="step"
                  :class="{
                    'active': index <= currentStepIndex(progress),
                    'completed': index < currentStepIndex(progress)
                  }"
                >
                  <div class="step-icon">
                    <i v-if="index < currentStepIndex(progress)" class="fas fa-check"></i>
                    <span v-else>{{ index + 1 }}</span>
                  </div>
                  <div class="step-label">{{ step.label }}</div>
                  <div class="step-line" v-if="index < adoptionSteps.length - 1"></div>
                </div>
              </div>
            </div>
            
            <div class="progress-details">
              <div class="detail-item">
                <span class="detail-label">当前步骤：</span>
                <span class="detail-value">{{ progress.current_step }}</span>
              </div>
              <div class="detail-item">
                <span class="detail-label">申请时间：</span>
                <span class="detail-value">{{ formatDate(progress.created_at) }}</span>
              </div>
              <div class="detail-item">
                <span class="detail-label">最后更新：</span>
                <span class="detail-value">{{ formatDate(progress.updated_at) }}</span>
              </div>
              <div class="detail-item" v-if="progress.notes">
                <span class="detail-label">备注：</span>
                <span class="detail-value">{{ progress.notes }}</span>
              </div>
            </div>
            
            <div class="progress-actions">
              <button class="action-btn contact-btn" @click="contactAdmin(progress)">
                <i class="fas fa-envelope"></i> 联系管理员
              </button>
              <button class="action-btn details-btn" @click="showProgressDetails(progress)">
                <i class="fas fa-info-circle"></i> 查看详情
              </button>
            </div>
          </div>
        </div>
        
        <div v-else class="empty-state">
          <div class="empty-icon">
            <i class="far fa-clipboard"></i>
          </div>
          <p class="empty-text">暂无领养进度</p>
          <router-link to="/adopt" class="browse-btn">
            <i class="fas fa-paw"></i> 浏览可领养宠物
          </router-link>
        </div>
      </div>
    </div>
    <Footer />
    
    <!-- 进度详情弹窗 -->
    <div v-if="selectedProgress" class="progress-modal" @click.self="selectedProgress = null">
      <div class="modal-content">
        <button class="close-btn" @click="selectedProgress = null">×</button>
        <h2>{{ selectedProgress.pet?.name }}的领养进度详情</h2>
        
        <div class="timeline">
          <div v-for="(event, index) in selectedProgress.timeline" :key="index" class="timeline-event">
            <div class="timeline-marker"></div>
            <div class="timeline-content">
              <h3>{{ event.step }}</h3>
              <p class="timeline-date">{{ formatDate(event.date) }}</p>
              <p v-if="event.notes" class="timeline-notes">{{ event.notes }}</p>
            </div>
          </div>
        </div>
        
        <div class="modal-actions">
          <button class="modal-btn close-modal" @click="selectedProgress = null">关闭</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import axios from 'axios';
import NavigationBar from '@/components/NavigationBar.vue';
import Footer from '@/components/Footer.vue';

// 领养流程步骤定义
const adoptionSteps = [
  { label: '申请提交', step: 'application_submitted' },
  { label: '资料审核', step: 'document_review' },
  { label: '家访安排', step: 'home_visit' },
  { label: '审核结果', step: 'approval' },
  { label: '签署协议', step: 'sign_contract' },
  { label: '完成领养', step: 'completed' }
];

const adoptionProgress = ref([]);
const selectedProgress = ref(null);

const getAdoptionProgress = async () => {
  try {
    const token = localStorage.getItem('token');
    if (!token) {
      throw new Error('用户未登录');
    }

    const response = await axios.get('http://localhost:3000/adoption-progress', {
      headers: { 
        Authorization: token,
        'Content-Type': 'application/json'
      }
    });

    if (response.status !== 200) {
      throw new Error(`请求失败，状态码: ${response.status}`);
    }

    adoptionProgress.value = response.data.map(item => ({
      ...item,
      pet: item.pet || { name: '未知宠物' } // 确保pet对象存在
    }));
    
  } catch (error) {
    console.error('获取领养进度失败:', error);
    
    let errorMessage = '获取领养进度失败，请重试';
    if (error.response) {
      // 服务器返回了错误响应
      errorMessage = error.response.data.error || errorMessage;
    } else if (error.request) {
      // 请求已发出但没有收到响应
      errorMessage = '无法连接到服务器，请检查网络连接';
    }
    
    alert(errorMessage);
  }
};

// 根据当前状态生成时间线
const generateTimeline = (progress) => {
  const timeline = [];
  const steps = [...adoptionSteps];
  
  // 添加申请提交事件
  timeline.push({
    step: '申请提交',
    date: progress.created_at,
    notes: '您的领养申请已成功提交'
  });
  
  // 根据当前状态添加其他事件
  if (progress.status === '审核中') {
    timeline.push({
      step: '资料审核中',
      date: progress.updated_at,
      notes: '工作人员正在审核您的申请资料'
    });
  } else if (progress.status === '审核通过') {
    timeline.push({
      step: '资料审核通过',
      date: progress.updated_at,
      notes: '您的申请资料已通过初步审核'
    });
    
    // 检查是否已完成家访
    if (progress.current_step.includes('家访')) {
      timeline.push({
        step: '家访安排',
        date: progress.home_visit_date || progress.updated_at,
        notes: progress.home_visit_notes || '家访已完成'
      });
    }
  } else if (progress.status === '审核拒绝') {
    timeline.push({
      step: '审核未通过',
      date: progress.updated_at,
      notes: progress.rejection_reason || '很遗憾，您的申请未能通过审核'
    });
  } else if (progress.status === '已完成') {
    timeline.push(
      {
        step: '资料审核通过',
        date: progress.approval_date || progress.updated_at,
        notes: '您的申请资料已通过审核'
      },
      {
        step: '家访完成',
        date: progress.home_visit_date || progress.updated_at,
        notes: '家访已完成且符合要求'
      },
      {
        step: '协议签署',
        date: progress.contract_date || progress.updated_at,
        notes: '领养协议已签署'
      },
      {
        step: '领养完成',
        date: progress.completed_date || progress.updated_at,
        notes: '恭喜您成功领养宠物！'
      }
    );
  }
  
  return timeline;
};

// 获取当前步骤的索引
const currentStepIndex = (progress) => {
  const step = adoptionSteps.find(s => s.step === progress.current_step);
  return step ? adoptionSteps.indexOf(step) : 0;
};

const getImageUrl = (imageName) => {
  return imageName ? new URL(`/src/assets/images/${imageName}`, import.meta.url).href : '';
};

const formatDate = (dateString) => {
  if (!dateString) return '暂无';
  const date = new Date(dateString);
  return date.toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  });
};

const getStatusClass = (status) => {
  switch (status) {
    case '审核中':
      return 'status-review';
    case '审核通过':
      return 'status-approved';
    case '审核拒绝':
      return 'status-rejected';
    case '已完成':
      return 'status-completed';
    default:
      return '';
  }
};

const showProgressDetails = (progress) => {
  selectedProgress.value = progress;
};

const contactAdmin = (progress) => {
  // 这里可以添加联系管理员的逻辑
  console.log('联系管理员关于:', progress.pet?.name);
  alert(`即将联系管理员关于${progress.pet?.name}的领养进度`);
};

onMounted(() => {
  getAdoptionProgress();
});
</script>

<style scoped>
@import url('https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css');

.page-container {
  padding: 20px 5%;
  min-height: calc(100vh - 120px);
  background-color: #f8f9fa;
}

.adoption-progress-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

h1 {
  font-weight: bold;
  color: #4a7c59;
  margin-bottom: 30px;
  font-size: 2.2rem;
  text-align: center;
}

.progress-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));
  gap: 20px;
  margin-top: 20px;
}

.progress-card {
  background-color: white;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
  padding: 20px;
  transition: transform 0.3s ease, box-shadow 0.3s ease;
}

.progress-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 16px rgba(0, 0, 0, 0.12);
}

.progress-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
  padding-bottom: 15px;
  border-bottom: 1px solid #eee;
}

.pet-info {
  display: flex;
  align-items: center;
  gap: 10px;
}

.pet-thumbnail {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  object-fit: cover;
}

.progress-header h2 {
  font-size: 1.4rem;
  color: #333;
  margin: 0;
}

.status-badge {
  padding: 5px 12px;
  border-radius: 20px;
  font-size: 0.85rem;
  font-weight: 600;
  color: white;
}

.status-review {
  background-color: #ff9800;
}

.status-approved {
  background-color: #4caf50;
}

.status-rejected {
  background-color: #f44336;
}

.status-completed {
  background-color: #2196f3;
}

/* 进度条样式 */
.progress-track {
  margin: 20px 0;
}

.progress-steps {
  display: flex;
  justify-content: space-between;
  position: relative;
}

.step {
  display: flex;
  flex-direction: column;
  align-items: center;
  position: relative;
  z-index: 1;
  flex: 1;
}

.step-icon {
  width: 30px;
  height: 30px;
  border-radius: 50%;
  background-color: #e0e0e0;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 8px;
  color: #fff;
  font-size: 14px;
}

.step.active .step-icon {
  background-color: #4a7c59;
}

.step.completed .step-icon {
  background-color: #4caf50;
}

.step-label {
  font-size: 12px;
  color: #757575;
  text-align: center;
  max-width: 80px;
  word-break: break-word;
}

.step.active .step-label {
  color: #333;
  font-weight: 500;
}

.step-line {
  position: absolute;
  top: 15px;
  left: calc(50% + 15px);
  right: calc(-50% + 15px);
  height: 2px;
  background-color: #e0e0e0;
  z-index: 0;
}

.step.completed + .step .step-line,
.step.active + .step .step-line {
  background-color: #4caf50;
}

.progress-details {
  margin-bottom: 20px;
}

.detail-item {
  display: flex;
  margin-bottom: 10px;
  font-size: 0.95rem;
}

.detail-label {
  font-weight: 600;
  color: #555;
  min-width: 80px;
}

.detail-value {
  color: #333;
}

.progress-actions {
  display: flex;
  gap: 10px;
  margin-top: 15px;
}

.action-btn {
  flex: 1;
  padding: 8px 12px;
  border: none;
  border-radius: 6px;
  font-size: 0.9rem;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.2s ease;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
}

.action-btn i {
  font-size: 0.9em;
}

.contact-btn {
  background-color: #f0f0f0;
  color: #555;
}

.contact-btn:hover {
  background-color: #e0e0e0;
}

.details-btn {
  background-color: #4a7c59;
  color: white;
}

.details-btn:hover {
  background-color: #3a6a49;
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 40px 20px;
  text-align: center;
}

.empty-icon {
  font-size: 4rem;
  color: #ccc;
  margin-bottom: 20px;
}

.empty-text {
  font-size: 1.2rem;
  color: #666;
  margin-bottom: 20px;
}

.browse-btn {
  padding: 10px 20px;
  background-color: #4a7c59;
  color: white;
  border-radius: 6px;
  text-decoration: none;
  font-weight: 600;
  transition: background-color 0.2s ease;
  display: inline-flex;
  align-items: center;
  gap: 8px;
}

.browse-btn:hover {
  background-color: #3a6a49;
}

/* 进度详情弹窗样式 */
.progress-modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.modal-content {
  background-color: white;
  border-radius: 12px;
  padding: 30px;
  max-width: 800px;
  width: 90%;
  max-height: 80vh;
  overflow-y: auto;
  position: relative;
}

.close-btn {
  position: absolute;
  top: 15px;
  right: 15px;
  background: none;
  border: none;
  font-size: 1.5rem;
  cursor: pointer;
  color: #666;
}

.modal-content h2 {
  color: #4a7c59;
  margin-bottom: 20px;
  text-align: center;
}

/* 时间线样式 */
.timeline {
  position: relative;
  padding-left: 30px;
  margin: 20px 0;
}

.timeline::before {
  content: '';
  position: absolute;
  top: 0;
  bottom: 0;
  left: 10px;
  width: 2px;
  background-color: #e0e0e0;
}

.timeline-event {
  position: relative;
  margin-bottom: 20px;
}

.timeline-marker {
  position: absolute;
  left: -30px;
  top: 5px;
  width: 20px;
  height: 20px;
  border-radius: 50%;
  background-color: #4a7c59;
}

.timeline-content {
  background-color: #f9f9f9;
  padding: 15px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.timeline-content h3 {
  margin: 0 0 5px 0;
  color: #333;
  font-size: 1.1rem;
}

.timeline-date {
  color: #666;
  font-size: 0.9rem;
  margin-bottom: 5px;
}

.timeline-notes {
  color: #444;
  margin: 0;
}

.modal-actions {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}

.modal-btn {
  padding: 8px 16px;
  border-radius: 6px;
  border: none;
  cursor: pointer;
  font-weight: 600;
}

.close-modal {
  background-color: #f0f0f0;
  color: #555;
}

.close-modal:hover {
  background-color: #e0e0e0;
}

@media (max-width: 768px) {
  .progress-list {
    grid-template-columns: 1fr;
  }
  
  .page-container {
    padding: 20px 3%;
  }
  
  .progress-steps {
    flex-wrap: wrap;
  }
  
  .step {
    flex: 0 0 33.333%;
    margin-bottom: 15px;
  }
  
  .step-line {
    display: none;
  }
}
</style>